package com.cjz.roomdbdemo.db;

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;

/**
 * 操作数据库的实际对象，单例！
 * <p>
 * 重点关注 {@link NoteDatabase#noteDao } 方法，该抽象方法自动实现
 * <p>
 * Created by cjz on 2018/8/31.
 */
@Database(entities = {Note.class}, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {

    private static NoteDatabase INSTANCE;

    public static NoteDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (NoteDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(), NoteDatabase.class, NoteDAO.databaseName)
//                            .addCallback(populateTestDataCallback)//填充测试数据
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    public abstract NoteDAO noteDao();

//填充测试数据
//    private static NoteDatabase.Callback populateTestDataCallback = new RoomDatabase.Callback() {
//        @Override
//        public void onOpen(@NonNull SupportSQLiteDatabase db) {
//            super.onOpen(db);
//            new PopulateTestDataAsyncTask(INSTANCE).execute();
//        }
//    };
//
//    private static class PopulateTestDataAsyncTask extends AsyncTask<Void, Void, Void> {
//
//        private final NoteDAO mDao;
//
//        PopulateTestDataAsyncTask(NoteDatabase db) {
//            mDao = db.noteDao();
//        }
//
//        @Override
//        protected Void doInBackground(final Void... params) {
//            mDao.deleteAll();
//            for (int i = 0; i < 20; i++) {
//                Note word = new Note("Hello" + i);
//                mDao.insert(word);
//            }
//            return null;
//        }
//    }
}